﻿namespace BlamanticUI.Components;

/// <summary>
/// Represents a progress bar in <see cref="Progress"/> component.
/// </summary>
[CssClass("bar")]
public class Bar : BlazorChildComponentBase<Progress,Bar>, IHasColor,IHasChildContent<double>
{
    /// <summary>
    /// The value of progress bar. If multiple, the sum of values unable to greater than 100.
    /// </summary>
    [Parameter]
    #if NET6_0_OR_GREATER
    [EditorRequired]
    #endif
    public double Value { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether to show percentage text.
    /// </summary>
    [Parameter] public bool ShowPercent { get; set; }
    /// <summary>
    /// Gets or sets a value indicating whether to align the text be centered.
    /// </summary>
    [Parameter] public bool Centered { get; set; }
    /// <summary>
    /// Gets or sets the color.
    /// </summary>
    [Parameter] [CssClass] public Color? Color { get; set; }
    /// <summary>
    /// A segment of UI content to render.
    /// </summary>
    [Parameter]public RenderFragment<double>? ChildContent { get; set; }

    /// <summary>
    /// Method invoked when the component has received parameters from its parent in
    /// the render tree, and the incoming values have been assigned to properties.
    /// </summary>
    protected override void OnParametersSet()
    {
        if (ShowPercent)
        {
            ChildContent = value => new RenderFragment(builder => builder.AddContent(0, $"{value}%"));
        }
    }

    protected override void AddContent(RenderTreeBuilder builder, int sequence)
    {
        if (ChildContent is not null)
        {
            builder.CreateElement(0, "div", ChildContent(Value), new
            {
                @class = HtmlHelper.CreateCssBuilder().Append("centered", Centered).Append("progress").ToString()
            });
        }
    }

    protected override void BuildStyle(IStyleBuilder builder)
    {
        builder.Append("transition-duration:300ms")
            .Append("display:block")
            .Append($"width:{Value}%")

            ;

        if (ParentComponent.ChildComponents.Count>1)
        {
            var barList = ParentComponent.ChildComponents;

            if (Index == 0)
            {
                builder.Append("border-top-right-radius:0px")
                    .Append("border-bottom-right-radius:0px");


            }
            else if (Index == barList.Count - 1)
            {
                builder.Append("border-top-left-radius:0px")
                    .Append("border-bottom-left-radius:0px");
            }
            else
            {
                builder.Append("border-radius:0px;");
            }
        }
    }
}
